﻿using System;
using System.Data;
using System.Data.Common;

namespace Songhay.Data.Activity
{
    /// <summary>
    /// The “default” base class of the Data Activity.
    /// </summary>
    /// <remarks>
    /// Because this base class implements an interface
    /// this definition can be bypassed entirely in favor of a new implementation
    /// based on this interface.
    /// </remarks>
    public class DataActivityAssembly : IDataActivityAssembly
    {

        #region IDataActivityAssembly Members

        /// <summary>
        /// Runs the data transformations of this component.
        /// </summary>
        /// <param name="accessItem">
        /// The specified <see cref="Songhay.Data.DataAccessItem"/>.
        /// </param>
        /// <remarks>
        /// The inheriting class should override this member.
        /// </remarks>
        public virtual void Execute(DataAccessItem accessItem) { }

        /// <summary>
        /// The log text of the Data Activity.
        /// </summary>
        public string Log
        {
            get { return this._log; }
        }

        /// <summary>
        /// The log-writing event of the Data Activity.
        /// </summary>
        public event EventHandler<OnWriteLogEventArgs> WriteLog;

        #endregion

        /// <summary>
        /// Events of the <see cref="System.Data.Common.DbConnection"/>.
        /// </summary>
        /// <param name="sender"> The event <see cref="System.Object"/>.</param>
        /// <param name="e">The event <see cref="System.Data.StateChangeEventArgs"/>.</param>
        protected void CnnStateChange(object sender, StateChangeEventArgs e)
        {
            if(sender is DbConnection)
            {
                DbConnection cnn = sender as DbConnection;
                switch(e.CurrentState)
                {
                    case (ConnectionState.Closed):
                        this.WriteToLog(String.Format("Connection closed.{0}", Environment.NewLine));
                        break;
                    case (ConnectionState.Open):
                        this.WriteToLog(String.Format("Connection to {0} open…{1}", cnn.DataSource, Environment.NewLine));
                        this.WriteToLog(String.Format("Current database: {0}.{1}", cnn.Database, Environment.NewLine));
                        break;
                }
            }
        }

        /// <summary>
        /// Appends log-event text to
        /// <see cref="Songhay.Data.Activity.DataActivityAssembly.Log"/>.
        /// </summary>
        /// <param name="newEntry">The log-event text.</param>
        protected void WriteToLog(string newEntry)
        {
            this._log += newEntry;
            OnWriteLogEventArgs e = new OnWriteLogEventArgs(newEntry);
            if(this.WriteLog != null) this.WriteLog(this, e);
        }

        private string _log;
    }
}
